package com.sankuai.velocity;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepository;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zengliang on 17/3/1.
 */

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "velocity_MainActivity";
    private TextView mTextView;
    private WebView mWebView;

    private long mStartTime;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTextView = (TextView) findViewById(R.id.textView);
        mWebView = (WebView) findViewById(R.id.webView);

        mStartTime = System.currentTimeMillis();

        mTextView.setText(velocityFromStringResource());
//        mTextView.setText(velocityFromAndroidResource());

        long time = System.currentTimeMillis() - mStartTime;
        Log.i(TAG, "time: " + time + "ms");

//        String htmlResult = velocityHtml();
//        mWebView.loadData(htmlResult, "text/html", "UTF-8");

    }

    /**
     * String 资源加载方式,Application下初始化时使用 initStringResourceVelocity()方法
     * @return
     */
    public String velocityFromStringResource() {
        String result = null;
        try {
            //1.初始化context,用来替换模板内容
            VelocityContext context = new VelocityContext();
            context.put("list", getNames());

            //2.输入模板文件
            StringResourceRepository repo = StringResourceLoader.getRepository();
            String myTemplateName = "erp";//缓存模板名称
            String myTemplate = "#set( $this = \"Velocity\")\n" +
                    "\n" +
                    "$this is great!\n" +
                    "\n" +
                    "#foreach( $name in $list )\n" +
                    "    $name is great!\n" +
                    "#end\n" +
                    "\n" +
                    "#set( $condition = true)\n" +
                    "\n" +
                    "#if ($condition)\n" +
                    "    The condition is true!\n" +
                    "#else\n" +
                    "    The condition is false!\n" +
                    "#end";
            repo.putStringResource(myTemplateName, myTemplate);
            Template template = null;
            try {
                template = Velocity.getTemplate(myTemplateName);
            } catch (ResourceNotFoundException rnfe) {
                Log.e(TAG, "Example : error : cannot find template " + myTemplate);
            } catch (ParseErrorException pee) {
                Log.e(TAG, "Example : Syntax error in template " + myTemplate + ":" + pee);
            }

            //3.输出到StringWriter
            StringWriter sw = new StringWriter();
            if (template != null) {
                template.merge(context, sw);
            }
            result = sw.toString();
            Log.i(TAG, "velocityTest1:" + result);

            sw.flush();
            sw.close();
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }

        return result;
    }


    /**
     * Android 资源加载方式，Application下初始化时使用 initAndroidResourceVelocity()方法
     * @return
     */
    public String velocityFromAndroidResource() {
        String result = null;
        try {
            //1.初始化context,用来替换模板内容
            VelocityContext context = new VelocityContext();
            context.put("list", getNames());

            //2.输入模板文件
            String templateFile = "example.vm";
            Template template = null;
            try {
                template = Velocity.getTemplate(templateFile);
            } catch (ResourceNotFoundException rnfe) {
                Log.e(TAG, "Example : error : cannot find template " + templateFile);
            } catch (ParseErrorException pee) {
                Log.e(TAG, "Example : Syntax error in template " + templateFile + ":" + pee);
            }
            //3.输出到StringWriter
            StringWriter sw = new StringWriter();
            if (template != null) {
                template.merge(context, sw);
            }
            result = sw.toString();
            Log.i(TAG, "velocityTest1:" + result);

            sw.flush();
            sw.close();
        } catch (Exception e) {
            Log.i(TAG, e.getMessage());
        }

        return result;
    }


    private Map<String, String> getErpMap(){
        Map<String,String > map = new HashMap();
        map.put("name","zgl");
        map.put("address","wangjingdonglu");
        map.put("phone","18612520013");
        return map;
    }

    private List<String> getErpList(){
        List<String> list = new ArrayList<>();

        list.add("ERP1");
        return list;
    }


    public ArrayList getNames() {
        ArrayList list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            list.add("ArrayList element " + i);

        }
        return list;
    }


    private String velocityTest2() {
        VelocityContext context = new VelocityContext();
        context.put("name", "Velocity");
        context.put("project", "Jakarta");

        String templateFile = "example2.vm";
        StringWriter sw = new StringWriter();
        try {
            Velocity.mergeTemplate(templateFile, "ISO-8859-1", context, sw);
        } catch (Exception e) {
            Log.e(TAG, "Problem merging template : " + e);
        }
        Log.i(TAG, " template : " + sw);

        /*String s = "We are using $project $name to render this.";
        sw = new StringWriter();
        try {
            Velocity.evaluate(context, sw, "logTag", s);
        } catch (ParseErrorException pee) {
            Log.e(TAG, "ParseErrorException : " + pee);
        } catch (MethodInvocationException mee) {
            Log.e(TAG, "MethodInvocationException : " + mee);
        } catch (Exception e) {
            Log.e(TAG, "Exception : " + e);
        }
        Log.i(TAG, "velocityTest2:\n" + " string : " + sw);*/

        return sw.toString();
    }



    /**
     * Android资源加载方式，替换html文件
     * @return
     */
    public String velocityHtml() {
        String result = null;
        try {
            VelocityContext context = new VelocityContext();
            context.put("erpItem", new ErpItem("meituandianping", 50));

            context.put("menuItems", getMenuItem());
            context.put("query", getErpMap());
            context.put("lists",getErpList());
            context.put("key1", "ribonucleic acid");



            Template template = Velocity.getTemplate("hello.html");

            StringWriter sw = new StringWriter();
            template.merge(context, sw);
            result = sw.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private List<String> getMenuItem(){
        List<String> menus = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            menus.add("menu" + i);
        }
        return menus;
    }


}
